package com.jiangyifen.robot.websocket.internal;

import java.io.IOException;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebsocketMessageRunnable implements Runnable {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebsocketMessageRunnable.class);

	private WebsocketMessage websocketMessage;

	public WebsocketMessageRunnable(WebsocketMessage websocketMessage) {
		this.setWebsocketMessage(websocketMessage);
	}

	@Override
	public void run() {

		if (websocketMessage.isExpired()) {
			LOGGER.debug("websocket 消息超时： clientid={}, msg={}", websocketMessage.getClientId(),
					websocketMessage.getMessage());
			return;
		} else {
			// 如果没有过期，就尝试发一下
			String clientId = websocketMessage.getClientId();
			Session session = WebsocketCache.connections.get(clientId);
			if ((session == null) || (!session.isOpen())) {
				// 如果发现没有对应的session（有可能是连接断了，也有可能是clientId传了错值）
				// 就把该msg拿出来，排到队列最后，避免因为它而影响后面的消息的发送
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					LOGGER.error(e.getMessage(), e);
				}
				WebsocketCache.unicastExecutor.execute(this);
				LOGGER.debug("websocket 重排！clientId={}, msg={}", websocketMessage.getClientId(),
						websocketMessage.getMessage());
				return;
			}
			try {
				synchronized (session) {
					session.getBasicRemote().sendText(websocketMessage.getMessage());
					LOGGER.debug("websocket 单发成功！clientId={}, message={}", websocketMessage.getClientId(),
							websocketMessage.getMessage());
				}
			} catch (IOException e) {
				LOGGER.error("websocket 单发失败！ clientId={}", websocketMessage.getClientId());
				LOGGER.error(e.getMessage(), e);
				// 如果发现websocket
				// session断开了，就清理掉这个websocket，并且把消息移动到队列最后等待重发
				// session
				WebsocketCache.connections.remove(clientId);

				try {
					session.close();
				} catch (IOException e1) {
					LOGGER.error(e1.getMessage(), e1);
				}

				WebsocketCache.unicastExecutor.execute(this);

				try {
					Thread.sleep(5);
				} catch (InterruptedException e1) {
					LOGGER.error(e1.getMessage(), e1);
				}

			}
		}

	}

	public WebsocketMessage getWebsocketMessage() {
		return websocketMessage;
	}

	public void setWebsocketMessage(WebsocketMessage websocketMessage) {
		this.websocketMessage = websocketMessage;
	}

}
